<template>
    <div>
        <div class="Frist_Home">
            <div class="main_topWarp">
                <div class="Frist_Home_back" >
                    <span class="Frist_Home_title">首页</span>
                </div>
            </div>
        </div>
         <div v-if="!isShow" class="Frist_Home_main">
            <div class="Frist_Home_nodata">
                    <img src="@/assets/img/home/kanban.png" alt="">
                    <div>暂无首页看板, </div>
                    <div>请先配置首页看板！</div>
            </div>
        </div>
        <div  v-if="isShow" style="padding-bottom: 80px;" >
            <!-- 搜索 -->
            <div class="dataBoard_search">
                <div v-for="(item,index) in lookForData"  class="dataBoard_search_item">
                    <!-- <div v-if="item.inputType=='单选'" @click.stop=" handleLabelClick(item)"> {{item.conditionName}}  {{selectedValues[item.id] || item.defaultValue}}<van-icon name="arrow" ></van-icon> </div> -->
                    <div  v-if="item.inputType=='单选'" >
                        <van-field
                            :label="item.conditionName"
                            v-model="selectedValues[item.id]"
                            placeholder="点击选择"
                            @click.stop=" handleLabelClick(item)"
                            readonly clickable
                        />
                    </div>
                    <!-- 下方弹框 -->
                    <template v-if=" showCalendar">
                        <van-popup v-model:show="showCalendar" round position="bottom">
                            <van-picker title="选择筛选条件" :columns="computedPickerColumns "
                                @confirm="(value) => onPickerConfirm(value, item.id)" 
                                @cancel="cancelPick"
                            />
                        </van-popup>
                    </template>
                    <!-- 多选 -->
                    <!-- 输入类型 -->
                    <div v-if="item.inputType === '输入'">
                        <van-field
                            :label="item.conditionName"
                            v-model="selectedValues[item.id]"
                            placeholder="请输入"
                            @blur="handleInputBlur(item.id)"
                            clearable
                            @clear="handleClear(item.id)"
                        />
                    </div>
                </div>
            </div>
            <!-- 指标 -->
            <div class="dataBoard_box" v-if="indicatorsData.length !== 0 ">
                <div class="title"><img src="@/assets/img/DataManagement/juxing.png" alt=""><div>{{indicatorsTitle}}</div></div>
                <div class="dataBoard_content">
                    <div class="dataBoard_indicators">
                        <div class="dataBoard_indicatorsInnerbox" v-for="(item, index) in indicatorsData" :key="item.key" 
                        >
                        <!-- :style="getRandomGradient()"> -->
                            <div class="num"> {{item.value}}</div>
                            <div>{{item.key}}</div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 图表 -->
            <div class="dataBoard_chartBox"  v-if="Object.keys(chartData).length > 0">
                <!-- <div class="title"><img src="@/assets/img/DataManagement/juxing.png" alt=""><div>{{ chartType == 'bar'? '柱状图': chartType=='line'? '折线图' : chartType=='pie'? '饼图' : '未知图类型'}}</div></div> -->
                <div class="title"><img src="@/assets/img/DataManagement/juxing.png" alt=""><div>{{chartTitle}}</div></div>
                <div class="content">
                    <div v-show="chartInstanceRef!==null" id="chartContainer" style="width: 100%;height:200px;"></div>
                </div>
            </div>

            <!-- 表格及分页 -->
            <div class="dataBoard_TabelBox" v-if="currentPageData.length !== 0" >
                <div class="title"><img src="@/assets/img/DataManagement/juxing.png" alt=""><div>{{tableTitle}}</div></div>
                <div class="content">
                    <div class="table-container">
                        <table  v-if="currentPageData&&currentPageData.length>0">
                            <thead>
                                <div class="thead-wrap" ref="theadWrap">
                                    <tr  class="tr_theadNew">  
                                        <th class="td_theadNew fixed-left staticCol" >序号</th>  
                                        <th class="scrollable-theadContent"  v-for="(value, key) in Object.keys(currentPageData[0])" :key="key">{{value}}</th>
                                    </tr>
                                </div>
                            </thead>
                            <tbody>
                                <div class="tbody-wrap" ref="tbodyWrap">
                                    <tr  v-for="(item, rowIndex) in currentPageData" :key="rowIndex" class="tr_new">
                                        <td class="td_new tbody-fixed-left staticCon" >{{ rowIndex + 1 }}</td>  
                                        <td class="scrollable-content" v-for="key in Object.keys(item)" :key="key">{{ item[key] || '--'}}</td>
                                    </tr>
                                </div>
                            </tbody>
                        </table>
                        <table v-else>
                            <div slot="no-results" class="noData" >
                                <div class="noData_container">
                                    <img src="@/assets/img/home/kanban.png" alt="">
                                    <div>暂无数据</div>
                                </div>
                            </div>
                        </table>
                    </div>

                    <!-- 分页 -->
                    <div class="myPagination">
                        <van-pagination 
                            class="inner_pagination"
                            v-model="currentPage" 
                            :total-items="completeData.length" 
                            :items-per-page="itemsPerPage"
                            :show-page-size="3" 
                            force-ellipses
                            @change="onPageChange"
                        />
                    </div> 

                </div>
            </div>
        </div>
        
        
        
    </div>
</template>

<script>
import { onBeforeMount, onMounted, reactive, ref, toRefs,watch,onUnmounted,computed  } from 'vue'
import { Toast, Notify} from 'vant';
import { useStore } from "vuex"; // ⚪️ 引入状态管理
import router from "@/router";
import { useRoute } from 'vue-router';
import { ShareDataGetShareFields, } from "@/network/DataManagement.js";
import { StoryBoardGetMobileData, StoryBoardGetConditionCascadeData,StoryBoardGetHomeMobileData} from "@/network/StoryBoard.js";

// 引入图表相关
// import * as echarts from 'echarts';
// 只导入需要的图表类型
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent, LegendComponent, DataZoomComponent } from 'echarts/components';
import { LineChart, BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers'; // 如果你想使用 Canvas 渲染器
// 注册必须的组件
echarts.use([
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  LineChart,
  BarChart,
  CanvasRenderer
]);


export default {
    setup() {
        // 获取当前路由信息
        const route = useRoute();
        const state = reactive({
            isShow:false,
            isLoading: false,
            myDataParams: route.query,
            fieldsData: [], // 后端返回的数据
            newFieldsData: [], // 前端生成数据
            storyParams:{ //查询参数
                // storyID: route.query.Id, //表示故事板ID
                storyID: '', //表示故事板ID
                storyTableID: "", //表示故事板的表的ID 596993a9-cc42-438d-9e56-3b759ff45911
                inputConditions: [ //用户输入的条件
                    // { name: "",	//条件的ID
                    //   value: ""		//条件的值
                    // }
                ],
                parentConditions: [],//下钻界面的上级数据作为条件
                dependencyValue: ""  //依赖值：比如城市，依赖值是某个省份，如湖南省，就表示为湖南省下面的所有城市
            }, 
            // 输入条件
            inputCondition:[],
            
            // 条件数据
            lookForData:[],
            currentItemId :null, //状态变量来存储当前点击项的 id
            selectedValues:{}, // 存储选中的值

            // 添加一个状态来保存搜索参数
            searchParams: {},

            // ==================
            searchDate:new Date(), //搜索日期
            showCalendar:false, //是否展示日期选择弹框
            
            // 指标名称
            indicatorsTitle:'',
            // 指标
            indicatorsData:[
                // {id:'1',indicatorName:'指标1',indicatorValue:'1231'},
                // {id:'2',indicatorName:'指标2',indicatorValue:'1211'},
                // {id:'3',indicatorName:'指标3',indicatorValue:'542'},
                // {id:'4',indicatorName:'指标4',indicatorValue:'754'},
                // {id:'5',indicatorName:'指标5',indicatorValue:'2145'},
                // {id:'6',indicatorName:'指标6',indicatorValue:'1643'},
                // {id:'7',indicatorName:'指标7',indicatorValue:'992'},
                // {id:'8',indicatorName:'指标8',indicatorValue:'1654'},
            ], //指标数据
            morandiColors1 : [
                "#EFF9F8", "#EEF7F9", "#EEF1F7", "#F8F4FF"
            ],
            morandiColors2 : [
                "#D9F6F0", "#D6E9F4", "#D8E0F9", "#ECDFFF"
            ],
            currentColorIndex: 0, // 初始化颜色索引
            
            // 图表
            chartData:{},
            chartTitle:'',
            chartInstance:null,
            chartType: 'bar',//图表类型_柱状
            chartType: 'line',//图表类型_折线图
            // chartType: 'pie',//图表类型_饼图
            legendData:[], //图例
            

            // 表格名称
            tableTitle:'',
            // 表格数据
            tableData:[],
            
            // 分页器
            currentPage:1,
            total:'8', //在搜索获取数据列表时，更新获取到的总条数
            perPage:'',//每页展示数量
            completeData:[], // 完整数据集
            currentPageData :[], // 当前页的数据
            itemsPerPage :10, // 每页显示的项目数量

        })
        let pickerOptions = reactive([]); // 筛选条件的值
        // 表单生成相关
        const formData = reactive([]);
        /*****************state**end*************************/ 
        // 计算属性来处理当pickerOptions为空时的显示
        const computedPickerColumns = computed(() => {
            // 直接返回 pickerOptions 或默认数组
            if (pickerOptions.length > 0) {
                return pickerOptions;
            }
            return [{ text: '暂无更多筛选条件', disabled: true }];
        });

        // 初始化挂载
        onMounted(() => {
            // 获取数据
            getInitlookForData()
            setTimeout(() => {
                state.lookForData.forEach((item) => {
                    state.selectedValues[item.id] = item.defaultValue || '';
                });
                buildSearchParams()
                // 获取数据
                getInitDataList()
            }, 500);
            // 初始化当前页数据
            updateCurrentPageData(state.currentPage);
            // console.log('传过来的数据',state.myDataParams);
            window.addEventListener('resize', handleWindowResize);
        });

        // 构建搜索参数
        const buildSearchParams=()=> {
            Object.keys(state.selectedValues).forEach(key => {
                if (state.selectedValues[key]) {
                state.storyParams.inputConditions.push({
                    name: key,
                    value: state.selectedValues[key]
                })
                }
            });
        }

        // 返回上一页
        const goBack=()=>{
            router.go(-1)
        }
        // 获取初始筛选条件
        const getInitlookForData=()=>{
            StoryBoardGetHomeMobileData(state.storyParams).then((res)=>{
                // console.log('后端返回的res',res.data);
                if(res.success==true ){
                    state.isShow=true
                    let lookForData=res.data.filter(item => item.controlType === "条件") || [];
                    state.lookForData=lookForData[0]?.returnData || [];
                }else{
                    state.isShow=false
                }
            })
            .catch((error) => {
                console.error("Error fetching data:", error);
            });    
        }
        // 获取我的数据条件筛选项
        const getInitDataList=()=>{
            // StoryBoardGetMobileData(state.storyParams).then((res)=>{
            StoryBoardGetHomeMobileData(state.storyParams).then((res)=>{
                // console.log('后端返回的res',res.data);
                if(res.success==true ){

                    state.isShow=true
                    let lookForData=res.data.filter(item => item.controlType === "条件") || [];
                    state.lookForData=lookForData[0]?.returnData || [];
                    
                    let chartData=res.data.filter(item => item.controlType === "图形") || {};
                    state.chartData=chartData[0]?.returnData  || {};
                    state.chartTitle=chartData[0]?.returnData.name || '';
                    let indicatorsData=res.data.filter(item => item.controlType === "指标") || [];
                    state.indicatorsData=indicatorsData[0]?.returnData || [];
                    state.indicatorsTitle=indicatorsData[0]?.name || '';
                    let tableData=res.data.filter(item => item.controlType === "表格") || [];
                    state.tableData=tableData[0]?.returnData || [];
                    state.tableTitle=tableData[0]?.name || '';
                    // 将完整数据集存储在 completeData 中
                    state.completeData = state.tableData;
                    // 初始化当前页数据
                    updateCurrentPageData(1);
                }else{
                    state.isShow=false
                }
            })
            .then(()=>{
                if(Object.keys(state.chartData).length > 0){
                    myChart()
                }else{
                    return
                }

            }) // 在数据处理完后立即调用 myChart
            .then(instance => {
                chartInstanceRef.value = instance;
            })
            .catch((error) => {
                console.error("Error fetching data:", error);
            });            

        } 
        // 下拉刷新
        const onRefresh = () => {
            getInitDataList()
            state.isLoading = false
        }

        
        /**********************条件start**********************/ 
        const handleLabelClick = (item) => {
            console.log('item', item);
            state.currentItemId = item.id;
            pickerOptions.length= 0; // 清空现有数组
             // 在数组最前面添加一个空字符串选项
             pickerOptions.unshift({ text: '空', value: '' });
            // 添加新项
            item.optionsValue.forEach(inner => {
                // pickerOptions.push(inner.key)
                let OptionsItem= { text: inner.key, value: inner.key }
                pickerOptions.push(OptionsItem)
            }); 
            
            state.showCalendar = true
        };
        // 取消
        const cancelPick = () => {
            state.showCalendar  = false
        }
        // 弹框确认选择（单选）
        const onPickerConfirm0 = (value) => {
            if (value.disabled) {
                state.showCalendar = false;
                return;
            }else{
                let id = state.currentItemId;
                // 更新 selectedValues
                state.selectedValues[id] = value.value;
                 // 检查是否有相同 id 的项，如果有则删除
                const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                if (existingIndex > -1) {
                    state.storyParams.inputConditions.splice(existingIndex, 1);
                }
                
                // 添加新的项
                state.storyParams.inputConditions.push({
                    name: id,
                    value: value.value
                })
                // console.log('查询参数',state.storyParams);
                
                state.currentPage=1; //当前页数要复原 
                // 触发搜索操作更新看板数据（包括state.indicatorsData总数据，更新total总数目）
                getInitDataList()
                state.showCalendar = false;
            }
            
        };
        const onPickerConfirm = (value) => {
            if (value.disabled) {
                state.showCalendar = false;
                return;
            } else {
                let id = state.currentItemId;
                // 更新 selectedValues
                state.selectedValues[id] = value.value;
                // 只有当 value 不为空时才继续处理
                if (value.value) {
                    // 检查是否有相同 id 的项，如果有则删除
                    const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                    if (existingIndex > -1) {
                        state.storyParams.inputConditions.splice(existingIndex, 1);
                    }
                    // 添加新的项
                    state.storyParams.inputConditions.push({
                        name: id,
                        value: value.value
                    });
                } else {
                    // 如果 value 为空，则删除对应的项
                    const indexToRemove = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                    if (indexToRemove > -1) {
                        state.storyParams.inputConditions.splice(indexToRemove, 1);
                    }
                }
                console.log('查询参数', state.storyParams);
                state.currentPage = 1; // 当前页数要复原 
                // 触发搜索操作更新看板数据（包括state.indicatorsData总数据，更新total总数目）
                getInitDataList();
                // 清理数组中的所有 value 为空的项
                state.storyParams.inputConditions = state.storyParams.inputConditions.filter(condition => condition.value !== '');
                state.showCalendar = false;
            }
        };

        // 弹框确认选择（多选）


        // 输入完成事件处理
        const handleInputBlur0 = (id) => {
            const value = state.selectedValues[id];
            if (value) {
                // 更新 inputConditions
                const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                if (existingIndex > -1) {
                state.storyParams.inputConditions.splice(existingIndex, 1, { name: id, value });
                } else {
                state.storyParams.inputConditions.push({ name: id, value });
                }
                
                // 触发搜索操作更新看板数据
                getInitDataList();
            }
        };
        const handleInputBlur = (id) => {
            const value = state.selectedValues[id];

            if (value) {
                // 更新 inputConditions
                const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                if (existingIndex > -1) {
                    state.storyParams.inputConditions.splice(existingIndex, 1, { name: id, value });
                } else {
                    state.storyParams.inputConditions.push({ name: id, value });
                }

                // 触发搜索操作更新看板数据
                getInitDataList();
            } else {
                // 如果 value 为空，则删除对应的项
                const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
                if (existingIndex > -1) {
                    state.storyParams.inputConditions.splice(existingIndex, 1);
                }
            }

            // 清理数组中的所有 value 为空的项
            state.storyParams.inputConditions = state.storyParams.inputConditions.filter(condition => condition.value !== '');
        };
        // 清除输入框内容时触发
        const handleClear = (id) => {
            state.selectedValues[id] = ''; // 清除选中的值
            // 更新 inputConditions
            const existingIndex = state.storyParams.inputConditions.findIndex(condition => condition.name === id);
            if (existingIndex > -1) {
                state.storyParams.inputConditions.splice(existingIndex, 1);
            }
            
            // 触发搜索操作更新看板数据
            getInitDataList();
        };
        /**********************条件end**********************/ 

        // ===================指标展示 start=======================
       const getRandomGradient=()=>{
            // 获取当前索引对应的颜色
            const color1 = state.morandiColors1[state.currentColorIndex];
            const color2 = state.morandiColors2[state.currentColorIndex];
            // 更新索引以准备下次调用，使用取余运算实现循环
            state.currentColorIndex = (state.currentColorIndex + 1) % state.morandiColors1.length;

            return {
                background: `linear-gradient(0deg, ${color1} 0%, ${color2} 99%)`
            };
       }

       const getRandomHexColor=()=>{
            return '#' + Math.floor(Math.random() * 152).toString(16);
       }

        // ===================指标展示 end=======================

        // ===================图表展示 start=======================
        // 图表自适应
        // 在state外部定义一个ref来保存图表实例
        const chartInstanceRef = ref(null);
        // 创建处理窗口大小变化的函数
        const handleWindowResize = () => {
            chartInstanceRef.value && chartInstanceRef.value.resize();
        };
        // 在mounted生命周期钩子中监听窗口大小变化
        // onMounted(() => {
        //     window.addEventListener('resize', handleWindowResize);
        //     // 确保图表实例被正确赋值
        //     myChart().then(instance => {
        //         chartInstanceRef.value = instance;
        //     });
        // });

        // 在unmounted生命周期钩子中移除监听器
        onUnmounted(() => {
            window.removeEventListener('resize', handleWindowResize);
        });

       // 图表配置
        const myChart=()=>{
            return new Promise((resolve) => {
                // 基于准备好的dom，初始化echarts实例
                let myChart = echarts.init(document.getElementById('chartContainer'));
                
                // X轴分类标签（categories）
                let Xdata = state.chartData.xValues;
                // let Ydata = state.chartData.series[0].yValues;
                state.legendData=state.chartData.series.map(item => item.name);

                // 配置图表
                let option = {}
                option = {
                    grid: {
                        x: 55,
                        y: 40,
                        x2: 15,
                        y2: 40
                    },
                    dataZoom: [
                        {
                            type: 'inside',
                            throttle: 50
                        }
                    ],
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross',
                        },
                        confine:true //将 tooltip 框限制在图表的区域内
                    },
                    xAxis: {
                        data: Xdata,
                        interval: 0, // 步长
                        type: 'category',
                        axisPointer: {
                            type: 'shadow'
                        },
                        // 坐标轴刻度文字相关设置。
                        axisLabel: {
                            rotate:45,
                            textStyle: {
                                fontSize: 11,
                                color: '#70778C',
                                fontWeight:400
                            }
                        },
                        // 坐标轴刻度相关设置
                        axisTick:{
                            show: false
                        },
                    },
                    yAxis: {
                        type: 'value',
                        // 坐标轴轴线相关设置。
                        axisLine: {
                            show: false,
                        },
                        // 坐标轴刻度相关设置
                        axisTick:{
                            show: false
                        },
                        // 平行与x轴的分割线设置
                        splitLine: {
                            lineStyle: {
                                color: ['#99999959'],
                                width: 1,
                                type: 'solid'
                            }
                        },
                        axisLabel: {
                            formatter: '{value}'
                        },
                        labels: {
                            align: 'left',
                            x: -8,
                            y: 5,
                            style: {
                                color: '#70778C'
                            }
                        },
                    },
                    legend: {
                        data: state.legendData,
                        textStyle: {
                            color: "#B4B4B4",
                            fontSize:11
                        },
                        top: "2px",
                    },
                    series: state.chartData.series.map((item, index) => ({
                        name: item.name,
                        type: item.chartType === '柱状图' ? 'bar' : 'line',
                        data: item.yValues,
                        color: getColor(index), // 自定义颜色函数
                        itemStyle: {
                            normal: {
                                // 渐变了
                                color:item.chartType === '柱状图' ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: getColor(index) },
                                    { offset: 1, color: lightenColor(getColor(index)) }
                                ]) :getColor(index) ,
                                // 调整数据点大小与线宽一致，这里假设线宽为4作为示例
                                symbolSize: 0,
                                // 设置柱子左右边框圆角为4px
                                borderRadius: [2, 2, 0, 0], // 设置上左和上右圆角为4px，下边无圆角
                            }
                        },
                        // 阴影区域
                        areaStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: getColor(index) },
                                { offset: 1, color: '#cbf1ff' }
                            ])
                        }
                        
                    }))
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
                resolve(myChart); // 在初始化完成后返回图表实例
            })
        };

        const  getColor=(index)=> {
            // 可以自定义颜色数组，这里使用 ECharts 提供的默认颜色
            const colors = [
                 '#00E4FF', '#0065FE','#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
            ];
            return colors[index % colors.length];
        }

        // 辅助函数，用于生成更浅的颜色
        const  lightenColor=(color)=> {
            var usePound = false;
            if (color[0] == "#") {
                color = color.slice(1);
                usePound = true;
            }
            var num = parseInt(color, 16);
            var r = (num >> 16) + 0.6 * 255;
            var b = ((num >> 8) & 0x00FF) + 0.6 * 255;
            var g = (num & 0x0000FF) + 0.6 * 255;
            return (usePound ? "#" : "") + (0x1000000 + (r < 255 ? r < 1 ? 0 : r : 255) * 0x10000 + (b < 255 ? b < 1 ? 0 : b : 255) * 0x100 + (g < 255 ? g < 1 ? 0 : g : 255)).toString(16).slice(1);
        }
        // ===================图表展示 end=======================

        // ===================分页器 start=======================
        // 更新当前页数据的方法
        const updateCurrentPageData = (page) => {
            const startIndex = (page - 1) * state.itemsPerPage;
            const endIndex = startIndex + state.itemsPerPage;
            state.currentPageData = state.completeData.slice(startIndex, endIndex);
        };
        
        // 监听currentPage的变化更新数据
        const onPageChange = (newPage) => {
            // 当currentPage变化时，调用更新数据的方法
            state.currentPage = newPage;
            updateCurrentPageData(newPage);
        };
        
        // 使用watch来监听 currentPage 的变化
        watch(() => state.currentPage, (newPage) => {
            updateCurrentPageData(newPage);
        }, { immediate: true });
        // ===================分页器 end=======================

        return {
            ...toRefs(state),
            ...toRefs(pickerOptions),
            // ...toRefs(chart),
            formData, 
            onRefresh,
            goBack,
            // 指标
            getRandomGradient,getRandomHexColor,
            // 图表
            getColor,
            myChart,
            // 分页器
            onPageChange,
            // 条件
            computedPickerColumns,
            handleLabelClick,cancelPick,onPickerConfirm,
            handleInputBlur,handleClear,
            buildSearchParams,getInitlookForData

        };
    },
};
</script>

<style scoped>
.AllCategories{
text-align: center;
padding-top: 40%;
/*p{
    font-size: 0.6rem;
    padding-top: 0.5rem;
}
    */
}
</style>